package com.league.blog.controller;

import com.league.blog.mapper.ArticleMapper;
import com.league.blog.mapper.MenuMapper;
import com.league.blog.mapper.UserMapper;
import com.league.blog.pojo.Menu;
import com.league.blog.pojo.User;
import com.league.blog.system.redis.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author 黄豪琦
 * 日期:2020-03-30 15:02
 * 说明:
 */
@Controller
@Slf4j
public class PublicController {

    private RedisUtils redisUtils;

    private ArticleMapper articleMapper;

    private UserMapper userMapper;

    private MenuMapper menuMapper;

    @Value("${images.path}")
    private String uploadedFolder;

    private static final String IMG_FORMAT = "jpg,jpeg,gif,png,bmp,webp";

    public PublicController(RedisUtils redisUtils) {
        this.redisUtils = redisUtils;
    }

    @RequestMapping("/images/{image}")
    public void outPutImage(@PathVariable("image")String imgName, HttpServletResponse response){
        if(imgName.substring(imgName.lastIndexOf(".")+1).contains(IMG_FORMAT)){
            imgName += ".png";
        }
        if(!uploadedFolder.contains(imgName)){
            imgName = uploadedFolder + imgName;
        }

        File imgFile = new File(imgName);
        FileInputStream fin;
        OutputStream output;
        try {
            output = response.getOutputStream();
            fin = new FileInputStream(imgFile);
            byte[] arr = new byte[1024 * 10];
            int n;
            while ((n = fin.read(arr)) != -1) {
                output.write(arr, 0, n);
            }
            output.flush();
            output.close();
        } catch (FileNotFoundException e){
            //没有这张图片，不处理
        } catch (IOException e) {
            String errorMsg = e.getMessage();
            if(errorMsg.contains("Broken pipe")){
                //管道断开 一般是客户端加载时间过长停止加载所引发的 问题不大 忽略
            } else {
                e.printStackTrace();
            }
        }
    }

    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @PostMapping("/login")
    public String loginsubmit(User user){
        String result;
        //添加用户认证信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getAccountName(),
                user.getUserPassword(), true);
        try {
            subject.login(token);
            User u = (User)subject.getPrincipal();
            Session session = subject.getSession();
            session.setAttribute("user", u);
            log.info("用户["+u.getAccountName()+"]登录了");
            result = "redirect:/p/" + user.getAccountName();
        } catch (LockedAccountException e){
            log.info("账号已被锁定\t"+e.getMessage());
            result = "login";
        }catch (AuthenticationException e) {
            log.info("密码错误\t"+e.getMessage());
            result = "login";
        }catch (Exception e) {
            log.info("出异常了\t"+e.getMessage());
            result = "login";
        }
        return result;
    }

    @RequestMapping("/")
    public String home1(){
        return "index";
    }

    @RequestMapping("/index")
    public String home2(){
        return "redirect:index";
    }

    @RequestMapping("/logout")
    public String logout(){
        SecurityUtils.getSubject().logout();
        return "index";
    }

    @ResponseBody
    @RequestMapping("/test")
    public User test(){
        return userMapper.selectUserByAccountName("admin");
    }

    @ResponseBody
    @RequestMapping("/menu")
    public Menu test2(){
        return menuMapper.selectRootMenu();
    }

    @Autowired
    public void setMenuMapper(MenuMapper menuMapper) {
        this.menuMapper = menuMapper;
    }

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Autowired
    public void setRedisUtils(RedisUtils redisUtils) {
        this.redisUtils = redisUtils;
    }

    @Autowired
    public void setArticleMapper(ArticleMapper articleMapper) {
        this.articleMapper = articleMapper;
    }

}
